# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
import arrow

class CybPipeline(object):

    collection_name = 'scrapy_items'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI','192.168.1.220:29001'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'chuangyebang_v1')
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        _id = item['_id']
        del(item['_id'])
        if item.get('_status') == 404:
            self.db.enterprise.update_one({'_id':_id},{'$set':item},upsert=True)
        try:
            self.db.enterprise.update_one({'_id':_id},{'$inc':{'version':1},'$set':item},upsert=True)
            self.db.enterprise_history.update_one({'_id':'%s_%s'%(_id,arrow.now().format('YYYYMMDD'))},{'$set':item},upsert=True)
        except pymongo.errors.DuplicateKeyError as e:
            print(e)

        return item
